import updateUserPhoto, {
  getUserProfile,
  updateUser,
} from '@/store/acitons/profile'
// import { RootState } from '@/types/store'
import { useInitValue } from '@/utils/hooks'
import {
  Button,
  List,
  DatePicker,
  NavBar,
  Popup,
  Toast,
  Dialog,
} from 'antd-mobile'
import classNames from 'classnames'
import { useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
// import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router'
import EditInput from './EditInput'
import EditList from './EditList'
import styles from './index.module.scss'
import dayjs from 'dayjs'
import { logout } from '@/store/acitons/login'
const Item = List.Item

const ProfileEdit = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  // 1.获取个人信息
  // const dispatch = useDispatch()
  // // 2.处理action
  // useEffect(() => {
  //   dispatch(getUserProfile())
  // }, [dispatch])
  // // 3. 获取数据进行渲染
  // const { userProfile } = useSelector((state: RootState) => state.profile)
  //
  const { userProfile } = useInitValue(getUserProfile, 'profile')
  // console.log(userProfile.name)

  // const [value, setValue] = useState((userProfile.name)

  //5.提供显示隐藏昵称和简介的弹出层
  type showState = {
    type: '' | 'name' | 'intro'
    visible: boolean
  }
  const [showInput, setShowInput] = useState<showState>({
    type: '',
    visible: false,
  })

  // 6.点击简介和昵称弹出层

  // 7.处理关闭
  const closeInput = () => {
    setShowInput({
      type: '',
      visible: false,
    })
    setShowList({
      type: '',
      visible: false,
    })
  }
  // 8.更新数据
  const onUpdate = async (key: string, value: string) => {
    // 9. 发请求对数据进行更新
    if (key === 'photo') {
      fileRef.current!.click()
      return
    }
    // console.log(key, value)
    await dispatch(updateUser(key, value))
    Toast.show({
      icon: 'success',
      content: '修改成功',
    })
    closeInput()
  }
  //10 修改头像和性别
  type showListType = {
    visible: boolean
    type: '' | 'gender' | 'photo'
  }
  const [showList, setShowList] = useState<showListType>({
    type: '',
    visible: false,
  })
  // 11 测试
  // const [value, setValue] = useState(userProfile.name)
  // 12.上传头像
  const fileRef = useRef<HTMLInputElement>(null)
  const changePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    // console.log(e.target.files![0])
    const file = e.target.files![0]
    const fd = new FormData()
    fd.append('photo', file)
    await dispatch(updateUserPhoto(fd))
    Toast.show({
      icon: 'success',
      content: '修改头像成功',
    })
    closeInput()
  }

  // 13.修改生日
  const [showBirthday, setShowBirthday] = useState(false)
  // 14.处理退出功能

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          onBack={() => history.go(-1)}
          style={{
            '--border-bottom': '1px solid #F0F0F0',
          }}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img width={24} height={24} src={userProfile.photo} alt="" />
                </span>
              }
              arrow
              onClick={() => {
                setShowList({ type: 'photo', visible: true })
              }}
            >
              头像
            </Item>

            <Item
              arrow
              extra={userProfile.name}
              onClick={() => {
                setShowInput({ type: 'name', visible: true })
              }}
            >
              昵称
            </Item>

            <Item
              onClick={() => {
                setShowInput({ type: 'intro', visible: true })
              }}
              arrow
              extra={
                <span className={classNames('intro', 'normal')}>
                  {userProfile.intro || '未填写'}
                </span>
              }
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              arrow
              extra={userProfile.gender === 0 ? '男' : '女'}
              onClick={() => {
                setShowList({ type: 'gender', visible: true })
              }}
            >
              性别
            </Item>
            <Item
              arrow
              extra={userProfile.birthday}
              onClick={() => setShowBirthday(true)}
            >
              生日
            </Item>
          </List>

          <DatePicker
            visible={false}
            value={new Date()}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
          />
        </div>

        {/* 简介 */}
        <Popup
          visible={showInput.visible}
          position="right"
          bodyStyle={{ minWidth: '60vw' }}
          destroyOnClose
        >
          <EditInput
            closeInput={closeInput}
            type={showInput.type}
            onUpdate={onUpdate}
          ></EditInput>
        </Popup>

        <Popup
          visible={showList.visible}
          destroyOnClose
          onMaskClick={() => setShowList({ type: '', visible: false })}
        >
          <EditList
            onUpdate={onUpdate}
            type={showList.type}
            closeInput={closeInput}
          ></EditList>
        </Popup>
      </div>
      <div className="logout">
        <Button
          className="btn"
          onClick={() => {
            Dialog.show({
              closeOnMaskClick: true,
              title: '温馨提示',
              content: '你确定要退出当前系统吗?',
              closeOnAction: true,
              actions: [
                [
                  {
                    key: 'cancel',
                    text: '取消',
                    bold: true,
                    style: {
                      color: 'blue',
                    },
                  },
                  {
                    key: 'confirm',
                    text: '确定',
                    bold: true,
                    danger: true,
                    onClick: () => {
                      dispatch(logout())
                      history.push('/login')
                    },
                  },
                ],
              ],
            })
          }}
        >
          退出登录
        </Button>
      </div>
      {/* 处理上传头像 */}
      <input type="file" hidden ref={fileRef} onChange={changePhoto} />

      {/* 生日 */}
      <DatePicker
        title="选择年月日"
        value={new Date(userProfile.birthday)}
        visible={showBirthday}
        min={new Date('1970-01-01')}
        max={new Date()}
        onClose={() => {
          setShowBirthday(false)
        }}
        onConfirm={(val) => {
          onUpdate('birthday', dayjs(val).format('YYYY-MM-DD'))
        }}
      />
    </div>
  )
}

export default ProfileEdit
